package com.example.server.impl;

import com.example.dao.jobMapper.JobMapper;
import com.example.dao.userMapper.UserMapper;
import com.example.dto.job.Job;
import com.example.dto.job.JobCriteria;
import com.example.exception.EntityExistException;
import com.example.server.JobServer;
import com.example.util.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class JobServerImpl implements JobServer {

    @Autowired
    private JobMapper jobMapper;
    private UserMapper userMapper;
    /**
     * 添加岗位
     *
     * @param job 岗位参数
     * @return Map<String, Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Job resources) {
        Job job = jobMapper.findByName(resources.getName());
        if(job != null){
            throw new EntityExistException(Job.class,"name",resources.getName());
        }
        jobMapper.save(resources);
    }

    /**
     * 查找岗位信息
     *
     * @param jobCriteria
     * @return Map<String, Object>
     */
    @Override
    public Map<String, Object> list(JobCriteria jobCriteria) {
        Map<String, Object> result = new HashMap<>(4);

        Map<String, Object> data = new HashMap<>();
        data.put("createTime", null);
        data.put("updateTime", null);
        data.put("blurry", jobCriteria.getBlurry());
        data.put("enabled", jobCriteria.getEnabled());
        data.put("page", jobCriteria.getPage());
        data.put("size", jobCriteria.getSize());

        List<Job> jobs = jobMapper.selectList(data);
        int count = jobMapper.findCount(data);
        result.put("content", jobs);
        result.put("totalElements", count);
        return result;
    }

    /**
     * 删除岗位信息
     *
     * @param
     * @return Map<String, Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        jobMapper.deleteAllByIdIn(ids);
    }

    /**
     * 修改岗位信息
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Job resources) {
        Job job = jobMapper.findByIds(resources.getId());
        Job old = jobMapper.findByNames(resources.getName());
        if(old != null && !old.getId().equals(resources.getId())){
            throw new EntityExistException(Job.class,"name",resources.getName());
        }
        ValidationUtil.isNull( job.getId(),"Job","id",resources.getId());
        resources.setId(job.getId());
        jobMapper.save(resources);
    }
}